package funcs

import (
	"context"

	"hundsun.com/hsl/hschain/common/cache"
	"hundsun.com/hsl/hschain/common/config"
	grpcutil "hundsun.com/hsl/hschain/common/util/grpc"
	"hundsun.com/hsl/hschain/protos/common"
)

const (
	//ConfigKeyEnableBlacklist ...
	ConfigKeyEnableBlacklist = "chain.enableBlacklist"
	//SystemAuthorityIdentifier ...
	SystemAuthorityIdentifier = "systemAuthority"
	//BlacklistKey ...
	BlacklistKey = "blacklist"
)

//VerifyBlacklist deprecated
func VerifyBlacklist(ctx context.Context, blklist *cache.Cache) bool {
	if !EnableBlacklist() || blklist == nil {
		return false
	}
	// 验证
	cert, err := grpcutil.GetCertFromContext(ctx)
	if err != nil {
		return true
	}
	if blklist.Contains(cert.SerialNumber.String()) {
		return true
	}
	return false
}

//EnableBlacklist deprecated
func EnableBlacklist() bool {
	return config.GetBoolConfigValue(ConfigKeyEnableBlacklist, false)
}

//GetBlacklist deprecated
func GetBlacklist() (*common.BlackLists, error) {
	// TODO 后续Blacklist通过 p2p 跟外部进行连接
	//instance := statedb.GetStateDbServiceInstance()
	//kv, err := instance.GetState(SystemAuthorityIdentifier, BlacklistKey)
	//if kv == nil || err != nil {
	//	return nil, err
	//}
	//lists := &common.BlackLists{}
	//err = proto.Unmarshal(kv.Value, lists)
	//if err != nil {
	//	return nil, err
	//}
	//return lists, nil
	return nil, nil
}

//UpdateBlacklist 保存在底层的健值对
// namespace + key  --- 这里key为合约地址，这里链上目前只有一个，因此定为BlacklistKey
// SystemAuthorityIdentifier + BlacklistKey
// deprecated
func UpdateBlacklist(lists *common.BlackLists) error {
	//v, err := proto.Marshal(lists)
	//if err != nil {
	//	return err
	//}
	//res := &ledger.NsKV{
	//	Namespace: SystemAuthorityIdentifier,
	//	Key:       BlacklistKey,
	//	Value:     v,
	//}
	//instance := statedb.GetStateDbServiceInstance()
	//return instance.PutState(res)
	return nil
}
